package com.frank.demo.aop.aspect;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;

import java.util.Date;

/**
 * AOP demo
 *
 * @author frank
 * @version 2017-02-03
 */
@Aspect
public class DemoAspect implements Ordered {
    private static Logger logger = LoggerFactory.getLogger(DemoAspect.class);

    /***
     * 　　 * 切点 　　
     */
    @Pointcut("@annotation(com.frank.demo.aop.annotation.Demo)")
//    @Pointcut("execution(public * as*(..))")
    public void allAddMethod() {
    }

    /***
     * 执行方法
     *
     * @throws Throwable
     *
     */
    @Around("allAddMethod()")
    public Object DemoMethod(ProceedingJoinPoint joinPoint) throws Throwable {

        //className
        logger.info("className:{}", joinPoint.getTarget().getClass().getName());
        //methodName
        logger.info("methodName:{}", joinPoint.getSignature().getName());
        // args
        StringBuffer sb = new StringBuffer();
        Object args[] = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            Object obj = args[i];
            if ((obj instanceof CharSequence) || (obj instanceof Number)
                    || (obj instanceof Character) || (obj instanceof Boolean)
                    || (obj instanceof Date)) {
                sb.append(obj.toString());
            } else {
                sb.append(ToStringBuilder.reflectionToString(obj, ToStringStyle.SIMPLE_STYLE));
            }
            sb.append(";");
        }
        logger.info("args:{}", sb.toString());

        joinPoint.proceed();

        return null;
    }

    @Before("allAddMethod()")
    public void before() {
        System.out.println("Before");
    }

    @After("allAddMethod()")
    public void After() {
        System.out.println("After");
    }

    @AfterReturning("allAddMethod()")
    public void AfterReturning() {
        System.out.println("AfterReturning");
    }

    @AfterThrowing("allAddMethod()")
    public void AfterThrowing() {
        System.out.println("AfterThrowing");
    }

    public int getOrder() {
        return -1;
    }
}
